﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FTchina;
using System.Text.RegularExpressions;
namespace FTchina.SMSServer
{
    /// <summary>
    ///SmsChannel 的摘要说明
    /// </summary>
    public class SmsChannel
    {
        private static string ChinaMobile = @"^(13[4-9]|15[0|1|2|7|8|9]|18[2|7|8]|147)\d{8}$";//移动

        private static string ChinaUnicom = @"^(13[0-2]|15[5|6]|18[5|6]|145)\d{8}$";//联通

        private static string ChinaTel = @"^(133|153|18[0|9])\d{8}$";//电信

        public SmsChannel()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }


        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="target"></param>
        /// <param name="content"></param>
        /// <param name="smsguid"></param>
        /// <returns></returns>
        public static Boolean Sned2Channel(string target, string content, string smsguid)
        {
            string Operator = GetOperatorByPhone(target);
            bool limitflag = true;
            int id = GetChannelID(Operator, out limitflag);

            FTchina.Models.Sms_Channel mSms_Channel;
            if (FTchina.Caching.FTchinaCache.IsExits("mSms_Channel" + id))
            {
                mSms_Channel = (FTchina.Models.Sms_Channel)HttpRuntime.Cache.Get("mSms_Channel" + id);
            }
            else
            {
                mSms_Channel = FTchina.BLL.Sms_ChannelManager.GetSms_ChannelByid(id);
                HttpRuntime.Cache.Insert("mSms_Channel" + id, mSms_Channel);
            }
            return Send2Server(mSms_Channel, limitflag, target, content, smsguid);
        }

        /// <summary>
        /// 获取要发送的最佳通道
        /// </summary>
        /// <param name="Operator"></param>
        /// <param name="limitflag"></param>
        /// <returns></returns>
        private static int GetChannelID(string Operator, out bool limitflag)
        {

            //将超过1小时的短信通道置为0，去除每小时的限制
            string ResetChannelSql = @"UPDATE    Sms_ChannelCounter
SET              sendcount = 0,lastDateTime='"+DateTime.Now.ToString()+"' "+
"WHERE     (DATEDIFF(Minute, lastDateTime, GETDATE()) > 60)";
            shujuku.ExecuteSql(ResetChannelSql);


            int id = 0;
            if (Operator == "ChinaUnicom")
            {
                id = 1;
                limitflag = false;
            }
            else
            {
                //离预定限制还有2条短信，选择时间更久远的通道  sc.limit - scc.sendcount AS cha  这是离达到阀门值的差
                string sql = @"SELECT     TOP (1) sc.limit - scc.sendcount AS cha, DATEDIFF(Minute, scc.lastDateTime, GETDATE()) AS Minute, sc.limit, scc.id, scc.SmsChannelID, scc.sendcount, 
                      scc.lastDateTime
FROM         Sms_ChannelCounter AS scc INNER JOIN
                      Sms_Channel AS sc ON scc.SmsChannelID = sc.id AND sc.limit - scc.sendcount > 4
ORDER BY cha DESC, Minute DESC";

                int.TryParse(shujuku.GetDataTable(sql).Rows[0]["SmsChannelID"].ToString(), out id);//取smschannelID
                limitflag = true;
            }

            return id;
        }



        private static Boolean Send2Server(FTchina.Models.Sms_Channel mSms_Channel, bool limit, string target, string content, string smsguid)
        {
            bool flag = true;
            //string tmp="COMMANDID=01&CORPID={Uname}&CPPW={upsw}&SOURCEADDRFLAG=1&SOURCEADDR={uname}&PHONE={target}&SMSID={smsguid}&CONTENT={content}&LICENSE={lices}";
            string poststr = mSms_Channel.Poststr.Replace("{uname}", mSms_Channel.Uname);
            poststr = poststr.Replace("{upsw}", MD5MK.MD5String(mSms_Channel.Upsw));
            poststr = poststr.Replace("{target}", target);
            poststr = poststr.Replace("{smsguid}", smsguid.Substring(0, 20));
            poststr = poststr.Replace("{content}", content);
            poststr = poststr.Replace("{lices}", mSms_Channel.Lices);

            System.Text.Encoding en = System.Text.Encoding.GetEncoding(mSms_Channel.Encoding);

           // LogNet.LogBLL.info(mSms_Channel.Url + poststr);
            string result = basic.Post2Http(mSms_Channel.Url, en, poststr);

            string Date = DateTime.Now.ToString();

            if (result.Trim() == mSms_Channel.SuccessString)
            {
                flag = true;
                //发送成功
                /****
                 * 1、更新Sms_sended的 result ,resulttime，channelID
                 * 2、如果是网间短信，将Sms_ChannelCounter 的sendcount+1，lastdatetime
                 * **/
                UpdateSendedState(result, Date, mSms_Channel.Id, smsguid);
                if (limit)
                {
                    UpdateChannelState(mSms_Channel.Id, Date);
                }
            }
            else
            {
                flag = false;
                /***
                 * 1、更新sms_log state
                 * 
                 * **/

                UpdateSmsLogState(smsguid, result, Date);
            }

            return flag;

        }




        /// <summary>
        /// 获取手机归属运营商
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        private static string GetOperatorByPhone(string target)
        {
            string tmp = string.Empty;
            target = target.Replace("+086", "").Replace("+86", "");
            Regex regCM = new Regex(ChinaMobile);
            Regex regCU = new Regex(ChinaUnicom);
            Regex regCT = new Regex(ChinaTel);

            if (regCM.Match(target).Success)
            {
                tmp = "ChinaMobile";
            }
            else
            {
                if (regCU.Match(target).Success)
                {
                    tmp = "ChinaUnicom";
                }
                else
                {
                    if (regCT.Match(target).Success)
                    {
                        tmp = "ChinaTel";
                    }
                    else
                    {//如果没有匹配成功的
                        tmp = "ChinaUnicom";
                    }
                }
            }

            return tmp;

        }



        /// <summary>
        /// 更新发送失败的短信
        /// </summary>
        /// <param name="smsguid"></param>
        /// <param name="result"></param>
        /// <param name="Date"></param>
        private static void UpdateSmsLogState(string smsguid, string result, string Date)
        {
            string sql = "update sms_log set state='{0}',statetime='{1}' where smsguid='{2}'";
            shujuku.ExecuteSql(string.Format(sql, result, Date, smsguid));
        }


        /// <summary>
        /// 更新网间发送短信计数器
        /// </summary>
        /// <param name="p"></param>
        /// <param name="Date"></param>
        private static void UpdateChannelState(long ChannelId, string Date)
        {
            string sql = "update Sms_ChannelCounter set sendcount=sendcount+1   where SmsChannelID='{0}'";
            shujuku.ExecuteSql(string.Format(sql,  ChannelId));
        }


        /// <summary>
        /// 更新发送成功的sms_sended
        /// </summary>
        /// <param name="result"></param>
        /// <param name="Date"></param>
        /// <param name="p"></param>
        /// <param name="smsguid"></param>
        private static void UpdateSendedState(string result, string Date, long ChannelId, string smsguid)
        {
            string sql = "update sms_sended set result='{0}',resulttime='{1}',channelID='{2}' where smsguid='{3}'";
            shujuku.ExecuteSql(string.Format(sql, result, Date, ChannelId, smsguid));
        }

    }
}